

#import "ImageBrowser.h"
#import <SDWebImage/SDImageCache.h>

#pragma mark - 自定义九宫格布局Cell
@interface PicCollectionViewCell : UICollectionViewCell
@property (nonatomic, weak) NSURL *imageURL;

/** <#note#> */
@property (nonatomic, weak) UIImageView *imageView;
@end

@implementation PicCollectionViewCell


-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        UIImageView *imageView = [[UIImageView alloc]initWithFrame:self.bounds];
        _imageView = imageView;
        _imageView.contentMode = UIViewContentModeScaleAspectFill;
        _imageView.clipsToBounds = YES;
        
        self.backgroundColor = [UIColor whiteColor];
        [self addSubview:imageView];
    }
    
    return self;
}



- (void)setImageURL:(NSURL *)imageURL{
    _imageURL = imageURL;
    if (_imageURL == nil) {
        return;
    }
    
    [_imageView sd_setImageWithURL:imageURL placeholderImage:nil options:kNilOptions];
    
}

- (void)layoutSubviews{
    
    [super layoutSubviews];
    
    self.imageView.frame = self.bounds;
}
@end


#pragma mark - 图片浏览器
@interface PhotoBrowserController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegate>
@property (nonatomic, weak) UICollectionView *collectionView;

@property (nonatomic, strong) NSIndexPath *didSelectIndex;

@property (nonatomic, strong) NSArray *picURLs;

@property (nonatomic, weak) UILabel *currutIdex;

+ (instancetype)photoBrowserControllerWith:(NSIndexPath *)index picURLs:(NSArray *)urls;
@end


#pragma mark - 自定义图片浏览器UICollectionViewCell
@interface PhotoBrowserCell : UICollectionViewCell<UIScrollViewDelegate>
@property (nonatomic, weak) NSURL *picURL;

@property (nonatomic, weak) UIImageView *imageView;

@property (nonatomic, strong)void(^dismissBlock)(void);
@end


#pragma mark - 自定义图片下载指示器
@interface PresentVC : UIPresentationController

@property (nonatomic, strong)NSArray *pics;

@property (nonatomic, strong)NSIndexPath *index;

@end

@implementation PresentVC

- (void)containerViewWillLayoutSubviews{
    [super containerViewWillLayoutSubviews];
    
    self.presentedView.frame = [UIScreen mainScreen].bounds;
    
}


@end


@implementation BrowserLayout

-(void)prepareLayout{
    [super prepareLayout];
    
    self.minimumInteritemSpacing = 8;
    self.minimumLineSpacing = 8;
    
    //    colletion.backgroundColor = [UIColor redColor];
}


- (CGSize)itemSizeWitUrls:(NSArray<NSURL *> *)urls withMargin:(CGFloat)leftRightMargin{
    NSInteger imageCount = urls.count;
    
    NSInteger col = 3.0;
    
    CGFloat margin = 8;
    
    CGFloat cellW = (KScreenW - (col - 1) * margin - leftRightMargin) / col;
    
    if (imageCount == 0) {
        
        return  CGSizeMake(0, 0);
        
    } else if (imageCount == 1){
        
        NSString *key = urls.firstObject.absoluteString;
        
        UIImage *tempImage = [[[SDWebImageManager sharedManager] imageCache] imageFromDiskCacheForKey:key];
        
        if ( tempImage == nil) {
            
            return CGSizeMake(0, 0);
            
        }else{
            
            ImageBrowser *borwer = (ImageBrowser *)self.collectionView;
            
            if (borwer.index != nil) {
                return CGSizeMake(0.2,0.2);
            } else {
                return CGSizeMake(KScreenW * 0.5, KScreenW * 0.5 / tempImage.size.width * tempImage.size.height);

            }
            
        }
        
        
        
        
    }else{
        
        
        return CGSizeMake(cellW, cellW);
        
    }
    
    
    
}



- (CGSize)myCollectionViewSizeWitUrls:(NSArray<NSURL *> *)urls withMargin:(CGFloat)leftRightMargin{
    NSInteger imageCount = urls.count;
    
    NSInteger col = 3.0;
    
    NSInteger row = -1;
    
    CGFloat margin = 8;
    
    CGFloat cellW = (KScreenW - (col - 1) * margin - leftRightMargin) / col;
    
    if (imageCount == 0) {
        
        return  CGSizeMake(0, 0);
        
    } else if (imageCount == 1){
        
        NSString *key = urls.firstObject.absoluteString;
        
        UIImage *tempImage = [[[SDWebImageManager sharedManager] imageCache] imageFromDiskCacheForKey:key];
        
        if ( tempImage == nil) {
            
            return CGSizeMake(0, 0);
            
        }else{
            
            
            return CGSizeMake(KScreenW * 0.5, KScreenW * 0.5 / tempImage.size.width * tempImage.size.height);
            
        }
        
        
        
    }else  if (imageCount == 2){
        
        row = 1;
        col = 2;
        CGFloat width = cellW * col + (col - 1) * margin;
        
        return CGSizeMake(width + 1, cellW + 1);
        
    }else if (imageCount == 4){
        
        row = 2;
        col = 2;
        CGFloat width = cellW * col + (col - 1) * margin;
        
        return CGSizeMake(width + 1, width + 1);
        
        
    }else{
        
        row = (imageCount - 1) / 3 + 1;
        col = 3;
        CGFloat width = cellW * col + (col - 1) * margin;
        CGFloat height = cellW * row + (row - 1) * margin;
        
        return CGSizeMake(width + 1, height + 1);
        
    }
    
    
    
}



@end

@interface ImageBrowser ()<UICollectionViewDelegate,UICollectionViewDataSource,UIViewControllerTransitioningDelegate,UIViewControllerAnimatedTransitioning>

@end

@implementation ImageBrowser{
    CGFloat _margin;
    CGSize _itemSize;
    NSInteger _maxColumns;
    NSString *_identifier;
    NSIndexPath *_didselectIndex;
    PhotoBrowserController *_dissmissVC;
    
}

-(void)awakeFromNib{
    
    [super awakeFromNib];
    
    _identifier = @"PicCollectionViewCell";
    [self registerClass:[PicCollectionViewCell class] forCellWithReuseIdentifier:_identifier];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(lookBtnDidTapGigImageDisplay:) name:@"LookBtnDidTapGigImageDisplay" object:nil];
    self.delegate = self;
    self.dataSource = self;
    
}

- (void)dealloc{
    
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}




- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return _thumPicURLs.count;
    
    
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    PicCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:_identifier forIndexPath:indexPath];
    
    cell.imageURL = _thumPicURLs[indexPath.item];
    
    
    return  cell;
    
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    _didselectIndex  = indexPath;
    NSArray *urls = self.bigPicURLs ? self.bigPicURLs : self.thumPicURLs;
    PhotoBrowserController *photoVC = [PhotoBrowserController photoBrowserControllerWith:indexPath picURLs:urls];
    photoVC.view.backgroundColor = themeColor;
    _dissmissVC = photoVC;
    
    photoVC.modalPresentationStyle = UIModalPresentationCustom;
    photoVC.transitioningDelegate = self;
    
    [[self viewController] presentViewController:photoVC animated:YES completion:nil];
}

- (void)lookBtnDidTapGigImageDisplay:(NSNotification *)notfi{
    
    NSIndexPath *notObjc = (NSIndexPath *)notfi.object;
    
    if ((notObjc.section == self.index.section)  && (notObjc.row == self.index.row)) {
    
        NSIndexPath *index = [NSIndexPath indexPathForItem:0 inSection:0];
        
        [self collectionView:self didSelectItemAtIndexPath:index];
    }
    
 
    
}


#pragma mark- 转场代理
- (nullable UIPresentationController *)presentationControllerForPresentedViewController:(UIViewController *)presented presentingViewController:(UIViewController *)presenting sourceViewController:(UIViewController *)source{
    PresentVC *presentVC = [[PresentVC alloc]initWithPresentedViewController:presented presentingViewController:presenting];
    return  presentVC;
    
}

- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source{
    return self;
}

- (nullable id <UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed{
    
    return  self;
    
}

- (NSTimeInterval)transitionDuration:(nullable id <UIViewControllerContextTransitioning>)transitionContext{
    
    return 0.5;
}

- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext{
    UIView *presentView = [transitionContext viewForKey:UITransitionContextToViewKey];
    
    if (presentView) {
        [[transitionContext containerView] addSubview:presentView];
        [transitionContext containerView].backgroundColor = [UIColor blackColor];
        UIImageView *imageVeiw = [[UIImageView alloc]init];
        imageVeiw.contentMode = UIViewContentModeScaleAspectFill;
        [imageVeiw sd_setImageWithURL:self.thumPicURLs[_didselectIndex.item]];
        [[transitionContext containerView] addSubview:imageVeiw];
        
        UICollectionViewCell *cell = [self cellForItemAtIndexPath:_didselectIndex];
        //计算初始位置
        imageVeiw.frame = [self convertRect:cell.frame toCoordinateSpace:[UIApplication sharedApplication].keyWindow];
        
        //计算结束位置
        NSURL *url = self.thumPicURLs[_didselectIndex.item];
        
        UIImage *image = [[[SDWebImageManager sharedManager] imageCache] imageFromDiskCacheForKey:url.absoluteString];
        CGFloat  screenH = [UIScreen mainScreen].bounds.size.height;
        CGFloat  screenW = [UIScreen mainScreen].bounds.size.width;
        CGFloat  imageH = screenW / image.size.width  * image.size.height;
        
        CGFloat  y = 0;
        if (imageH < screenH) {
            y = (screenH - imageH) * 0.5;
        }else{
            y = 0;
            
        }
        
        CGRect  endRect = CGRectMake(0, y, screenW, imageH);
        
        
        //执行动画
        presentView.alpha = 0.0;
        [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
            imageVeiw.frame = endRect;
            
        } completion:^(BOOL finished) {
            [transitionContext completeTransition:YES];
            presentView.alpha = 1.0;
            [imageVeiw removeFromSuperview];
            
        }];
        
        
        
        
        
    } else {
        //取出消失的View
        UIView *disView =  [transitionContext viewForKey:UITransitionContextFromViewKey];
        
        //获取动画的imageView
        UIImageView *imageView = [[UIImageView alloc]init];
        PhotoBrowserCell *cell = _dissmissVC.collectionView.visibleCells.firstObject;
        imageView.image = cell.imageView.image;
        imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageView.clipsToBounds = YES;
        
        CGFloat  screenH = [UIScreen mainScreen].bounds.size.height;
        CGFloat  screenW = [UIScreen mainScreen].bounds.size.width;
        CGFloat  imageH = screenW / imageView.image.size.width  * imageView.image.size.height;
        
        CGFloat  y = 0;
        if (imageH < screenH) {
            y = (screenH - imageH) * 0.5;
        }else{
            y = 0;
            
        }
        
        imageView.frame = CGRectMake(0, y, screenW, imageH);
        
        [[transitionContext containerView] addSubview:imageView];
        
        [transitionContext containerView].backgroundColor = [UIColor clearColor];
        
        
        [disView removeFromSuperview];
        
        
        //结束坐标
        NSIndexPath *idex = _dissmissVC.collectionView.indexPathsForVisibleItems.firstObject;
        PicCollectionViewCell *cell1 = (PicCollectionViewCell *)[self cellForItemAtIndexPath:idex];
        cell1.alpha = 0.0;
        
        CGRect endRect = [self convertRect:cell1.frame toCoordinateSpace:[UIApplication sharedApplication].keyWindow];
        
        //        self.presentDelegate.alpha = 0.0;
        [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
            imageView.frame = endRect;
            
        }completion:^(BOOL finished) {
            cell1.alpha = 1.0;
            [imageView removeFromSuperview];
            [transitionContext completeTransition:YES];
            
        }];
        
        
        
        
        
        
    }
    
}



- (UIViewController *)viewController {
    
    //通过响应者链，取得此视图所在的视图控制器
    UIResponder *next = self.nextResponder;
    do {
        
        //判断响应者对象是否是视图控制器类型
        if ([next isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)next;
        }
        
        next = next.nextResponder;
        
    }while(next != nil);
    
    return nil;
}

@end







#pragma mark - 自定义下载进度视图
@interface PhotoBrowserProgressView:UIView

@property (nonatomic, assign) CGFloat currtProgress;
@end

@implementation PhotoBrowserProgressView
- (void)setCurrtProgress:(CGFloat)currtProgress{
    _currtProgress = currtProgress;
    [self setNeedsDisplay];
    
}

- (void)drawRect:(CGRect)rect{
    [super drawRect:rect];
    CGPoint center = CGPointMake(rect.size.width * 0.5, rect.size.height * 0.5);
    CGFloat radius = rect.size.width * 0.5 -3;
    CGFloat starAngle = -M_PI_2;
    CGFloat endAngle = (CGFloat)(2 * M_PI) * _currtProgress + starAngle;
    
    UIBezierPath *bezipath = [UIBezierPath bezierPathWithArcCenter:center radius:radius startAngle:starAngle endAngle:endAngle clockwise:YES];
    
    [bezipath addLineToPoint:center];
    
    [bezipath closePath];
    
    
    [[UIColor grayColor] setFill];
    
    
    [bezipath fill];
    
}


@end







@implementation PhotoBrowserCell{
    UIScrollView *_scrollView;
    
    PhotoBrowserProgressView *_photoBrowserProgressView;
    
}

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        UIImageView *imageView = [[UIImageView alloc]init];
        _imageView = imageView;
        imageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imageViewClick:)];
        [imageView addGestureRecognizer:tap];
        
        UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imageViewDubClick:)];
        tap2.numberOfTapsRequired = 2;
        [imageView addGestureRecognizer:tap2];
        
        [tap requireGestureRecognizerToFail:tap2];
        UIScrollView *scroll = [[UIScrollView alloc]initWithFrame:self.contentView.bounds];
        CGRect rect = scroll.frame;
        rect.size.width -=20;
        scroll.frame = rect;
        [self.contentView addSubview:scroll];
        _scrollView = scroll;
        [scroll addSubview:imageView];
        
        scroll.delegate = self;
        scroll.minimumZoomScale = 1.0;
        scroll.maximumZoomScale = 2.0;
        
        if (@available(iOS 11.0, *)) {
            
            scroll.contentInsetAdjustmentBehavior = UIApplicationBackgroundFetchIntervalNever;
            
        }
        
        PhotoBrowserProgressView *progress = [[PhotoBrowserProgressView alloc]initWithFrame:CGRectMake(([UIScreen mainScreen].bounds.size.width - 50) / 2.0, ([UIScreen mainScreen].bounds.size.height - 50) / 2.0, 50, 50)];
        progress.hidden = YES;
        progress.layer.cornerRadius = 25;
        progress.layer.masksToBounds = YES;
        progress.backgroundColor = [UIColor lightGrayColor];
        _photoBrowserProgressView  = progress;
        [self.contentView addSubview:progress];
        
        
    }
    
    
    return self;
}


- (void)setPicURL:(NSURL *)picURL{
    _picURL = picURL;
    
    UIImage *image = [[[SDWebImageManager sharedManager] imageCache] imageFromDiskCacheForKey:_picURL.absoluteString];
    
    CGFloat screenH = [UIScreen mainScreen].bounds.size.height;
    CGFloat screenW = [UIScreen mainScreen].bounds.size.width;
    
    CGFloat imageViewH = screenW / image.size.width * image.size.height;
    // 重置放大缩小的比例
    _scrollView.zoomScale = 1.0;
    _imageView.frame = CGRectMake(0, 0, screenW, imageViewH);
    _scrollView.contentSize = _imageView.frame.size;
    
    // 5.设置内边距,确定imageView的位置
    CGFloat topInset = 0;
    if (imageViewH < screenH) { // 短图
        topInset = (screenH - imageViewH) * 0.5;
    } else { // 长图
        topInset = 0;
        _scrollView.contentOffset = CGPointZero;
    }
    _scrollView.contentInset = UIEdgeInsetsMake(topInset, 0, 0, 0);
    
    
    
    _photoBrowserProgressView.hidden = NO;
    //    NSString *bigURL = [picURL.absoluteString stringByReplacingOccurrencesOfString:@"thumbnail" withString:@"bmiddle"];
    //    @"http://www.17sucai.com/upload/510819/2016-04-01/9915bbdaa3b0bc9d7f52ba10e5098ed9.jpg"r
    
    [[SDWebImageManager sharedManager] downloadImageWithURL:_picURL options:kNilOptions progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        
        _photoBrowserProgressView.currtProgress = (CGFloat)receivedSize/expectedSize;
        
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        
        _imageView.image = image;
        _photoBrowserProgressView.hidden = YES;
    }];
    
    
    
    
    
    
    
}


- (void)imageViewClick:(UIGestureRecognizer *)gest{
    if (self.dismissBlock) {
        self.dismissBlock();
    }
    
    
}

- (void)imageViewDubClick:(UIGestureRecognizer *)gest{
    
    [UIView animateWithDuration:0.5 animations:^{
        
        _scrollView.zoomScale = 1;
        
        
    }];
    
    
    CGFloat imageH = _imageView.frame.size.height;
    CGFloat imageW = _imageView.frame.size.width;
    
    CGFloat screenH = [UIScreen mainScreen].bounds.size.height;
    CGFloat screenW = [UIScreen mainScreen].bounds.size.width;
    
    CGFloat topInset = imageH < screenH ? (screenH - imageH) * 0.5 : 0;
    CGFloat leftInset = imageW < screenW ? (screenW - imageW) * 0.5 : 0;
    
    [UIView animateWithDuration:0.5 animations:^{
        
        _scrollView.contentInset = UIEdgeInsetsMake(topInset, leftInset, topInset, leftInset);
        
        
    }];
    
    
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    
    return _imageView;
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale{
    CGFloat imageH = view.frame.size.height;
    CGFloat imageW = view.frame.size.width;
    
    CGFloat screenH = [UIScreen mainScreen].bounds.size.height;
    CGFloat screenW = [UIScreen mainScreen].bounds.size.width;
    
    CGFloat topInset = imageH < screenH ? (screenH - imageH) * 0.5 : 0;
    CGFloat leftInset = imageW < screenW ? (screenW - imageW) * 0.5 : 0;
    
    scrollView.contentInset = UIEdgeInsetsMake(topInset, leftInset, topInset, leftInset);
    
    
    
}


@end





@implementation PhotoBrowserController

+ (instancetype)photoBrowserControllerWith:(NSIndexPath *)index picURLs:(NSArray *)urls{
    PhotoBrowserController *photoVC = [[PhotoBrowserController alloc]init];
    photoVC.didSelectIndex = index;
    photoVC.picURLs = urls;
    return photoVC;
    
}

- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.itemSize  = self.view.bounds.size;
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        UICollectionView *coll = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
        coll.showsHorizontalScrollIndicator = NO;
        coll.pagingEnabled = YES;
        coll.dataSource = self;
        coll.delegate = self;
        coll.backgroundColor = [UIColor blackColor];
        [coll registerClass:[PhotoBrowserCell class] forCellWithReuseIdentifier:NSStringFromClass([PhotoBrowserCell class])];
        _collectionView = coll;
        
        [self.view addSubview:_collectionView];
    }
    
    return _collectionView;
    
}




- (void)viewDidLoad {
    [super viewDidLoad];
    CGRect rect = self.view.frame;
    rect.size.width +=20;
    self.view.frame = rect;
    [self.collectionView scrollToItemAtIndexPath:self.didSelectIndex atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:NO];
    
    [self addToolButton];
    // Do any additional setup after loading the view.
}

- (void)addToolButton{
    
    UILabel *currutIdex = [[UILabel alloc]init];
    
    if (IPhoneX) {
        
        currutIdex.frame = CGRectMake(0, 44, [UIScreen mainScreen].bounds.size.width, 35);
        
    } else {
        
        currutIdex.frame = CGRectMake(0, 20, [UIScreen mainScreen].bounds.size.width, 35);
    }
    
    currutIdex.textColor = [UIColor whiteColor];
    currutIdex.font = [UIFont systemFontOfSize:26];
    currutIdex.textAlignment = NSTextAlignmentCenter;
    self.currutIdex = currutIdex;
    self.currutIdex.text = [NSString stringWithFormat:@"%ld/%ld",self.didSelectIndex.item + 1,(unsigned long)_picURLs.count];
    [self.view addSubview:currutIdex];
    
    
    UIButton *closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    if (IPhoneX) {
        
        closeBtn.frame = CGRectMake(10, [UIScreen mainScreen].bounds.size.height - 74, 75, 30);
        
    } else {
        
        closeBtn.frame = CGRectMake(10, [UIScreen mainScreen].bounds.size.height - 40, 75, 30);
    }
    
    closeBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [closeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    closeBtn.backgroundColor = colorWithA(100, 100, 100, 0.7);
    [closeBtn addTarget:self action:@selector(closeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [closeBtn setTitle:@"关闭" forState:UIControlStateNormal];
    [self.view addSubview:closeBtn];
    closeBtn.layer.cornerRadius = 8;
    
    
    UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    if (IPhoneX) {
        
        saveBtn.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 85, [UIScreen mainScreen].bounds.size.height - 74, 75, 30);
        
    } else {
        
        saveBtn.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 85, [UIScreen mainScreen].bounds.size.height - 40, 75, 30);
    }
    saveBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    saveBtn.layer.cornerRadius = 8;
    [saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [saveBtn addTarget:self action:@selector(saveBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [saveBtn setTitle:@"保存图片" forState:UIControlStateNormal];
    saveBtn.backgroundColor = colorWithA(100, 100, 100, 0.7);
    [self.view addSubview:saveBtn];
    
    
    
    
}


- (void)closeBtnClick:(UIButton *)btn{
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}


- (void)saveBtnClick:(UIButton *)btn{
    PhotoBrowserCell *cell = (PhotoBrowserCell *)[self.collectionView visibleCells].firstObject;
    
    UIImage *image = cell.imageView.image;
    
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    NSString *message;
    if (error == nil) {
        message = @"保存成功";
        [SVProgressHUD showSuccessWithStatus:message];
        
    }else{
        message = @"保存失败";
        [SVProgressHUD showErrorWithStatus:message];
    }
    
    
}


#pragma mark - 图片浏览器中UICollectionView数据源方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.picURLs.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    PhotoBrowserCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([PhotoBrowserCell class]) forIndexPath:indexPath];
    
    cell.backgroundColor = [UIColor blackColor];
    
    cell.picURL = self.picURLs[indexPath.item];
    __weak  typeof(self)  weakSelf = self;
    cell.dismissBlock = ^{
        
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
        
        
    };
    
    return cell;
}


#pragma mark - 图片浏览器中UICollectionView代理方法
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSIndexPath *idex = self.collectionView.indexPathsForVisibleItems.firstObject;
    self.currutIdex.text = [NSString stringWithFormat:@"%ld/%ld",idex.item + 1,(unsigned long)_picURLs.count];
}


//- (BOOL)prefersStatusBarHidden{
//
//    return YES;
//
//}
@end




